package geo.campus;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

public class Map extends MapActivity implements LocationListener{

	private MapView mapView;
	private MapController mc;
	private GeoPoint location;
	private MyLocationOverlay mlo;
	private LocationManager lm;
	private SharedPreferences shpr;
	private Road mRoad;
	private ListOverlay itemizedoverlay;
	private Drawable poi;
	private ProgressDialog progressdialog;

	private final Activity act = this;

	private double londep;
	private double latdep;
	private double lonarr;
	private double latarr;
	private String addrarr = "";
	private String nomarr = "";
	private Location loc;
	private PopUp popup;
	private boolean sat = false;

	private static final int CODE_RET_OPT = 1;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		//récupération de l'id de la carte
		mapView = (MapView) findViewById(R.id.mapView);

		mapView.setBuiltInZoomControls(true);
		this.mc = mapView.getController();
		this.mlo = new MyLocationOverlay(getApplicationContext(), mapView);
		lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
		lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this);
		mlo.runOnFirstFix(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				mc.animateTo(mlo.getMyLocation());
				mc.setZoom(19);
			}
		});
		//loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		//latdep = loc.getLatitude();
		//londep = loc.getLongitude();
		mapView.getOverlays().add(mlo);
		mlo.enableMyLocation();
		shpr = PreferenceManager.getDefaultSharedPreferences(act);
		poi = this.getResources().getDrawable(R.drawable.ic_launcher);
		itemizedoverlay = new ListOverlay(poi);
		popup = new PopUp(act);
		getPreferences();
		mapView.invalidate();
		debutact();
		progressdialog = new ProgressDialog(this);
	}

	private void getPreferences()
	{
		sat = shpr.getBoolean("sat", false);
		mapView.getOverlays().clear();
		mapView.getOverlays().add(mlo);
		if(shpr.getBoolean("administration", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Administration");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("enseignement", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Enseignement");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("restaurant", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Restaurant Universitaire");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("cafeteriat", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Cafeteriat");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("bibliotheque", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Bibliotheque Universitaire");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("sante", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Sante - Sport");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("culture", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Culture");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("amphitheatre", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Amphitheatre");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("residence", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Residence Universitaire");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		if(shpr.getBoolean("Laboratoire", false))
		{
			ArrayList<OverlayItem> al = popup.affiche_poi("Laboratoire");
			for(int i = 0; i < al.size(); i++)
				itemizedoverlay.addOverlay(al.get(i));
			mapView.getOverlays().add(itemizedoverlay);
		}

		mapView.setSatellite(sat);
		mapView.invalidate();
	}

	public void debutact()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setMessage("Appuyer sur la touche menu de votre téléphone")
		.setCancelable(false)
		.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu2,menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_iti2 :
			popup.dialog(false, false);
			popup.setFini(false);
			new Thread(){
				public void run()
				{
					while(!popup.isFini())
					{

					}
					if(popup.isParcoursfixe())
					{
						latarr = popup.getLatarr();
						lonarr = popup.getLonarr();
						//latdep = loc.getLatitude();
						//londep = loc.getLongitude();
						latdep = 47.842937;
						londep = 1.936485;
						
						iti_select(latdep, londep, latarr, lonarr, popup.isPieton());
					}
				}
			}.start();

			return true;
		case R.id.menu_search2:
			popup.recdialog(false);
			popup.setFinires(false);
			new Thread(){
				public void run()
				{
					while(!popup.isFinires())
					{
						
					}
					reshandler.sendEmptyMessage(0);
				}
			}.start();
			break;
		case R.id.menu_preferences2:
			startActivityForResult(new Intent(this, Preferences.class), CODE_RET_OPT);
			break;
		case R.id.menu_info2:
			startActivity(new Intent(this, Info.class));
			break;
		default:
			break;
		}


		return super.onOptionsItemSelected(item);
	}

	private Handler reshandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0)
			{
				GeoPoint gp = new GeoPoint((int)popup.getLatarr()*1000000, (int)popup.getLonarr()*1000000);
				OverlayItem oi = new OverlayItem(gp, popup.getNomarr(), popup.getAddrarr());
				itemizedoverlay.addOverlay(oi);
				mapView.getOverlays().clear();
				mapView.getOverlays().add(itemizedoverlay);
				mapView.getOverlays().add(mlo);
				mapView.invalidate();
			}
		}
	};

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0)
			{
				MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
				mapView.getOverlays().clear();
				mapView.getOverlays().add(mlo);
				mapView.getOverlays().add(mapOverlay);
				mapView.invalidate();
			}
		};
	};

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0) {
				progressdialog.setMessage("Chargement en cours");
				progressdialog.show();
			}
		}
	};

	private static InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}

	public GeoPoint getLocation() {
		return location;
	}

	public void setLocation(GeoPoint location) {
		this.location = location;
		this.mc.setCenter(this.location);
		mapView.invalidate();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return true;
	}

	protected void onActivityResult(int ident, int code_retour, Intent retour)
	{
		if(ident == CODE_RET_OPT)
		{
			Toast.makeText(this, "Modifications terminées", Toast.LENGTH_SHORT).show();
			getPreferences();
		}
		super.onActivityResult(ident, code_retour, retour);
	}

	public void iti_select(final double fromLat, final double fromLon, final double toLat, final double toLon, final boolean pieton)
	{
		handler.sendEmptyMessage(0);
		new Thread() {
			@Override
			public void run() {
				String url = RoadProvider.getUrl(fromLat,fromLon, toLat, toLon, pieton);
				InputStream is = getConnection(url);
				mRoad = RoadProvider.getRoute(is);
				mHandler.sendEmptyMessage(0);
				progressdialog.dismiss();
			}
		}.start();
	}

	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		GeoPoint gp = new GeoPoint((int) (location.getLatitude()*1000000.0), (int) (location.getLongitude()*1000000.0));
		mc.animateTo(gp);
		mc.setZoom(mapView.getZoomLevel());
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public String getNomarr() {
		return nomarr;
	}

	public void setNomarr(String nomarr) {
		this.nomarr = nomarr;
	}

	public String getAddrarr() {
		return addrarr;
	}

	public void setAddrarr(String addrarr) {
		this.addrarr = addrarr;
	}

}

